package viv.karaoke.book;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ufsDataSource {

  // Database fields
  private SQLiteDatabase database;
  private mySQLiteHelper dbHelper;
    
  private String[] ufsColumns = {
		  						 mySQLiteHelper.VIEW_FAVOURITE_ID,
		  						 mySQLiteHelper.VIEW_FAVOURITE_SONG_NAME, 
		  						 mySQLiteHelper.VIEW_FAVOURITE_SONG_ARTIST, 
		  						 mySQLiteHelper.VIEW_FAVOURITE_USER_ID, 
		  						 mySQLiteHelper.VIEW_FAVOURITE_USER_NAME
		  						 };

  public ufsDataSource(Context context) {
    dbHelper = new mySQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

  public List<userFavouriteSong> getAllUfss(long userId) {
    List<userFavouriteSong> ufss = new ArrayList<userFavouriteSong>();
    
    String whereClause = mySQLiteHelper.VIEW_FAVOURITE_USER_ID + " = " + userId;
    
    Cursor cursor = database.query(mySQLiteHelper.VIEW_FAVOURITE, ufsColumns, 
					whereClause, null, null, null, null, null);
    
	try{
	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	    	userFavouriteSong ufs = cursorToUfs(cursor);
	      ufss.add(ufs);
	      cursor.moveToNext();
	    }
	}
	catch(Exception ex)
	{
	}
    finally
    {
    	//Make sure to close the cursor
    	cursor.close();
    }
    return ufss;
  }
  
  public List<song> getAllSongByUserId(long userId) {
	    List<song> songList = new ArrayList<song>();
	    
	    String whereClause = mySQLiteHelper.VIEW_FAVOURITE_USER_ID + " = " + userId;
	    
	    Cursor cursor = database.query(mySQLiteHelper.VIEW_FAVOURITE, ufsColumns, 
						whereClause, null, null, null, null, null);
	    
		try{
		    cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		    	userFavouriteSong ufs = cursorToUfs(cursor);
		    	
		    	song songItem = new song();
		    	songItem.setSongId(ufs.getSongId());
		    	songItem.setSongName(ufs.getSongName());
		    	songItem.setArtist(ufs.getArtist());
		    	
		      songList.add(songItem);
		      cursor.moveToNext();
		    }
		}
		catch(Exception ex)
		{
		}
	    finally
	    {
	    	//Make sure to close the cursor
	    	cursor.close();
	    }
	    return songList;
	  }
  
private userFavouriteSong cursorToUfs(Cursor cursor) 
{
	userFavouriteSong ufs = new userFavouriteSong();
    ufs.setFavouriteId(cursor.getLong(0));
    ufs.setSongId(cursor.getLong(1));
    ufs.setSongName(cursor.getString(2));
    ufs.setArtist(cursor.getString(3));
    ufs.setUserId(cursor.getLong(4));
    ufs.setUserName(cursor.getString(5));
    
    return ufs;
  }
}